import React, {useState,useEffect} from "react";
import {map, trim} from "lodash";
import {Modal, Form, Input, Select} from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {useQueryEnumsItems} from "@/services/enums";
import {UserProfile} from "@/components/proptypes";
import ContractAmount from "@/services/contractamount";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import DatePicker from "antd/lib/date-picker";
import moment from "moment";
function CreateAmountDialog({ amount_id,contractsid, dialog }) {
  const {optionsLoaded, options } = useQueryEnumsItems('amount_enum');
  const [dataLoaded, setDataLoaded] = useState(amount_id ===0 ? true : false);
  const [bill_date, setbill_date] = useState(moment());
  const [amount_enum, setamount_enum] = useState("");
  const [amount, setamount] = useState(0);
  const [finishamount, setfinishamount] = useState(0);
  const [message, setmessage] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateAmountEnabled = useState(true);//policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (amount_id === 0) return;

    let cancelLoading = false;
    ContractAmount.get({id:amount_id}).then(data => {
      if (!cancelLoading) {
        setbill_date(moment(data.bill_date));
        setamount_enum(data.amount_enum);
        setmessage(data.message);
        setDataLoaded(true);
    }});

    return () => {
      cancelLoading = true;
    };
  }, [amount_id]);

  function handlebill_dateChange(event) {
    const value = moment(event);
    setbill_date(value);
    setIsValid(value !== "" && amount_enum !== "" && amount_enum !== "");
  }
  function handleamount_enumChange(event) {
    const value = trim(event);
    setamount_enum(value);
    setIsValid(value !== "" && bill_date !== "" && amount_enum !== "");
  }
  function handlemessageChange(event) {
    const value = trim(event.target.value);
    setmessage(value);
    setIsValid( amount_enum !== "" && bill_date !== "" && amount_enum !== "");
  }
  function handleamountChange(event) {
    const value = trim(event.target.value);
    setamount(value);
    setIsValid(value !== "" && amount_enum !== "" && bill_date !== "");
  }
  function handlefinishamountChange(event) {
    const value = trim(event.target.value);
    setfinishamount(value);
    setIsValid( amount_enum !== "" && bill_date !== "" && amount_enum !== "");
  }
  function handleSubmit() {
    setSaveInProgress(true);
    let items={
        id: amount_id,
        userid: currentUser.id,
        bill_date: bill_date,
        contractsid: contractsid,
        amount_enum: amount_enum,
        amount: amount,
        finishamount: finishamount,
        message: message,
        sourcetype: "",
        sourceid: 0,
    }
    if (amount_id === 0) {
      ContractAmount.create(items)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    } else {
      ContractAmount.save(items)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateAmountEnabled ? {} : { footer: null })}
      title="款项计划"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateAmountDialogExtra" disabled={!isCreateAmountEnabled}>
      <Form>
        <Form.Item style={{ marginBottom: 5 }} label="计划日期">
        <DatePicker
          defaultValue={bill_date}
          onChange={handlebill_dateChange}
          placeholder="计划日期"
          disabled={saveInProgress}
        />
        </Form.Item>
        {optionsLoaded && (
        <Form.Item style={{ marginBottom: 5 }} label="款项类型">
          <Select style={{ width:  300 }}
                  defaultValue={amount_enum}
                  onChange={handleamount_enumChange}
                  disabled ={saveInProgress}>
            {map(options, ds => (
            <Select.Option key={ds.value} value={ds.value}>{ds.title}</Select.Option>
          ))}
        </Select>
        </Form.Item>
        )}
        <Form.Item style={{ marginBottom: 5 }} label="金额(¥)">
          <Input
            value={amount}
            onChange={handleamountChange}
            placeholder="金额(¥)"
            onkeyup="this.value=this.value.replace(/\D/g,'')"
            onafterpaste="this.value=this.value.replace(/\D/g,'')"
            type="number"
            disabled ={saveInProgress}
          />
        </Form.Item>
        {/* <Form.Item style={{ marginBottom: 5 }} label="执行金额(¥)">
          <Input
            value={finishamount}
            onChange={handlefinishamountChange}
            placeholder="执行金额(¥)"
            onkeyup="this.value=this.value.replace(/\D/g,'')"
            onafterpaste="this.value=this.value.replace(/\D/g,'')"
            type="number"
            disabled ={saveInProgress}
          />
        </Form.Item> */}
        <Form.Item style={{ marginBottom: 5 }} label="记录事项">
          <textarea
            rows="5"  cols="50"
            textAlignVertical="top"
            height="100px"
            value={message}
            onChange={handlemessageChange}
            placeholder="记录事项"
            disabled ={saveInProgress}
          />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="提醒时间">
        <DatePicker
          defaultValue={bill_date}
          onChange={handlebill_dateChange}
          placeholder="提醒时间"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="提醒内容">
          <textarea
            rows="5"  cols="50"
            textAlignVertical="top"
            height="100px"
            value={message}
            onChange={handlemessageChange}
            placeholder="提醒内容"
            disabled ={saveInProgress}
          />
        </Form.Item>
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateAmountDialog.propTypes = {
  amount_id: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateAmountDialog);
